Skip to main content

Bean 构造函数带参数的方式

构造函数带参数

  1. Bean 类
package cn.asdasd.java.ioc;

public class Bean {
private AnotherBean anotherBean;
private String string;

public Bean(AnotherBean anotherBean, String string) {
this.anotherBean = anotherBean;
this.string = string;
}

public AnotherBean getAnotherBean() {
return anotherBean;
}

public void setAnotherBean(AnotherBean anotherBean) {
this.anotherBean = anotherBean;
}

public String getString() {
return string;
}

public void setString(String string) {
this.string = string;
}

@Override
public String toString() {
return "Bean{" +
"anotherBean=" + anotherBean +
", string='" + string + '\'' +
'}';
}
}

  1. AnotherBean
package cn.asdasd.java.ioc;

public class AnotherBean {
}

  • XMl
    <bean id="anotherBean" class="cn.asdasd.java.ioc.AnotherBean"></bean>
<bean id="bean" class="cn.asdasd.java.ioc.Bean">
<constructor-arg index="0" name="anotherBean"
type="cn.asdasd.java.ioc.AnotherBean"
ref="anotherBean" />
<constructor-arg index="1" name="string"
type="java.lang.String"
value="aaa" />
</bean>
  • 测试类
package cn.asdasd.java.ioc.test;

import cn.asdasd.java.ioc.Bean;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class IocTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Bean bean = context.getBean("bean", Bean.class);
System.out.println("bean === " +bean);
}
}